<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Orchid\Attachment\Models\Attachment;
use Orchid\Filters\Filterable;
use Orchid\Filters\Types\Like;
use Orchid\Filters\Types\Where;
use Orchid\Filters\Types\WhereDateStartEnd;

class Post extends Model
{
    use Filterable;
    protected $fillable = [
        'user_id', 
        'category_id', 
        'title', 
        'slug', 
        'excerpt',
        'content', 
        'status', 
        'published_at', 
        'cover_image_id',
        'views'
    ];
    
    protected $casts = [
        'published_at' => 'datetime',
    ];
    
    /**
     * The attributes for which you can use filters in url.
     *
     * @var array
     */
    protected $allowedFilters = [
        'id'           => Where::class,
        'title'        => Like::class,
        'status'       => Where::class,
        'category_id'  => Where::class,
        'user_id'      => Where::class,
        'published_at' => WhereDateStartEnd::class,
        'created_at'   => WhereDateStartEnd::class,
        'updated_at'   => WhereDateStartEnd::class,
    ];
    
    /**
     * The attributes for which can use sort in url.
     *
     * @var array
     */
    protected $allowedSorts = [
        'id',
        'title',
        'status',
        'published_at',
        'created_at',
        'updated_at',
    ];
    
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
    
    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }
    
    public function coverImage()
    {
        return $this->belongsTo(Attachment::class, 'cover_image_id');
    }
    
    public function getContent()
    {
        return \Illuminate\Support\Str::limit($this->content, 50);
    }
    
    // 作用域：仅获取已发布的文章
    public function scopePublished($query)
    {
        return $query->where('status', 'published')
                     ->where('published_at', '<=', now());
    }
}
